package com.mySampleApplication.client.codeRule;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.mySampleApplication.client.dmp.DmpDto;
import com.mySampleApplication.client.dmp.DmpService;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.VerticalAlignment;
import com.smartgwt.client.util.JSOHelper;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.CloseClickEvent;
import com.smartgwt.client.widgets.events.CloseClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.SelectOtherItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.HStack;
import com.smartgwt.client.widgets.layout.VLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用法
 *      // 创建按钮和事件处理
 *      Button addButton = new Button("Add");
 *      addButton.setShowRollOver(true);
 *      addButton.setShowDown(true);
 *      addButton.addClickHandler(event -> showAddDialog(listGrid));
 *     private static void showAddDialog(ListGrid listGrid) {
 *       Window dialog=SShowWindow.getShowWindow();
 *       dialog.show();
 *     }
 */
public class SbWindow {
    public static Window getShowWindow(int status, int width, int height, String title, final ListGridRecord record, ListGrid listGrid, boolean istrue){
        final Window winModal = new Window();
        //winModal.setAutoSize(true);
        winModal.setWidth(width);
        winModal.setHeight(height);
        winModal.setTitle(title);
        winModal.setShowMinimizeButton(false);
        winModal.setIsModal(true);
        winModal.setShowModalMask(true);
        winModal.setCanDragReposition(true);
        winModal.setCanDragResize(true);
        winModal.centerInPage();
        winModal.addCloseClickHandler(new CloseClickHandler() {
            public void onCloseClick(CloseClickEvent event) {
                winModal.destroy();
            }
        });
        DynamicForm form = new DynamicForm();
        form.setPadding(20);
        form.setWidth100();
        form.setHeight(height-100);
        form.setNumCols(5);
        form.setCellPadding(10);

//        TextItem db_model_idField = new TextItem("db_model_id", "数据模型");
//        db_model_idField.setRequired(true);
        TextItem mcField = new TextItem("mc", "规则名称");
        mcField.setRequired(true);
        TextItem msField = new TextItem("ms", "描述");
        TextItem fgfField = new TextItem("fgf", "分隔符");
        TextItem qzField = new TextItem("qz", "前缀");
        TextItem hzField = new TextItem("hz", "后缀");
        TextItem bbField = new TextItem("bb", "版本");
        bbField.setValue(1);
        bbField.disable();
        SelectItem db_model_idField= new SelectItem("db_model_id", "数据模型");
        DmpService.App.getInstance().selectObjectList(new AsyncCallback<DmpDto>() {
            public void onSuccess(DmpDto result) {
                Map<String, String> keyValueMap = result.getKeyValueMap();
                db_model_idField.setValueMap(keyValueMap); // 设置静态数据
                //SC.say( "获取数据成功！");
            }
            public void onFailure(Throwable caught) {
                SC.warn("获取数据失败！");
            }
        });
//        SelectOtherItem db_model_idField = new SelectOtherItem();
//        db_model_idField.setTitle("数据模型");
//        db_model_idField.setName("db_model_id");
//        db_model_idField.setRequired(true);
//        db_model_idField.setValueMap("Ea", "Pkt", "Bag", "Ctn");
        if (record != null) {
            // 编辑模式下，将已有数据显示在表单中
            db_model_idField.setValue(record.getAttribute("db_model_id"));
            mcField.setValue(record.getAttribute("mc"));
            msField.setValue(record.getAttribute("ms"));
            fgfField.setValue(record.getAttribute("fgf"));
            qzField.setValue(record.getAttribute("qz"));
            hzField.setValue(record.getAttribute("hz"));
            // 禁用表单
            form.setDisabled(istrue);
            if(status==0){
                bbField.setValue(record.getAttribute("bb"));
            }else {
                bbField.setValue(Integer.parseInt(record.getAttribute("bb"))+1);
            }
        }

        Button saveButton = new Button("保存");
        saveButton.addClickHandler(event -> {
            if (form.validate()) {
                if (record != null) {
                    // 更新已有记录
                    record.setAttribute("db_model_id", db_model_idField.getValueAsString());
                    record.setAttribute("mc", mcField.getValueAsString());
                    record.setAttribute("ms", msField.getValueAsString());
                    record.setAttribute("fgf", fgfField.getValueAsString());
                    record.setAttribute("qz", qzField.getValueAsString());
                    record.setAttribute("hz", hzField.getValueAsString());
                    record.setAttribute("bb", bbField.getValueAsString());
//                    listGrid.updateData(record);
                    Map<String, String> map = new HashMap<>();
                    map.put("id", record.getAttribute("id"));
                    map.put("db_model_id", db_model_idField.getValueAsString());
                    map.put("mc", mcField.getValueAsString());
                    map.put("ms", msField.getValueAsString());
                    map.put("fgf", fgfField.getValueAsString());
                    map.put("qz", qzField.getValueAsString());
                    map.put("hz", hzField.getValueAsString());
                    map.put("bb", bbField.getValueAsString());
                    CodeRuleService.App.getInstance().setSbUpdate(map,new AsyncCallback<String>() {
                        public void onSuccess(String result) {

                            Map<String, String> mapPage = new HashMap<>();
                            mapPage.put("pageSize", "1");
                            mapPage.put("pageNumber", "10");
                            List<ListGridRecord> recordList = new ArrayList<>();
                            CodeRuleService.App.getInstance().getSelect(new HashMap<>(), mapPage, new AsyncCallback<CodeRuleDto>() {
                                public void onSuccess(CodeRuleDto result) {
                                    List<Map<String, String>> keyValueMap = result.getKeyValueMap();
                                    for (Map<String, String> data : keyValueMap) {
                                        ListGridRecord record = new ListGridRecord();
                                        data.forEach((k, v) -> {
                                            record.setAttribute(k, v);
                                        });
                                        // 设置其他需要的属性
                                        recordList.add(record);

                                    }
                                    listGrid.setData(recordList.toArray(new ListGridRecord[0]));
                                    SC.say( "升版成功！");
                                    //list.addAll(result);
                                }

                                public void onFailure(Throwable caught) {
                                    SC.warn("获取数据失败！");
                                }
                            });
//                            SC.say( "升版成功！");
//                            listGrid.updateData(record);
                            //list.addAll(result);
                        }

                        public void onFailure(Throwable caught) {
                            SC.warn("RPC failed");
                        }
                    });

                    listGrid.updateData(record);

                } else {
                    // 添加新记录
                    ListGridRecord newRecord = new ListGridRecord();
                    newRecord.setAttribute("db_model_id", db_model_idField.getValueAsString());
                    newRecord.setAttribute("mc", db_model_idField.getValueAsString()+"编码规则");
                    newRecord.setAttribute("ms", msField.getValueAsString());
                    newRecord.setAttribute("fgf", fgfField.getValueAsString());
                    newRecord.setAttribute("qz", qzField.getValueAsString());
                    newRecord.setAttribute("hz", hzField.getValueAsString());
                    newRecord.setAttribute("status", "禁用");
                    newRecord.setAttribute("bb", bbField.getValueAsString());

                    Map<String, String> map = new HashMap<>();
                    map.put("db_model_id", db_model_idField.getValueAsString());
                    map.put("mc", db_model_idField.getValueAsString()+"编码规则");
                    map.put("ms", msField.getValueAsString());
                    map.put("fgf", fgfField.getValueAsString());
                    map.put("qz", qzField.getValueAsString());
                    map.put("hz", hzField.getValueAsString());
                    map.put("status", "禁用");
                    map.put("bb", bbField.getValueAsString());
                    CodeRuleService.App.getInstance().setInsert(map,new AsyncCallback<String>() {
                        public void onSuccess(String result) {
                            Map<String, String> mapPage = new HashMap<>();
                            mapPage.put("pageSize", "1");
                            mapPage.put("pageNumber", "10");
                            List<ListGridRecord> recordList = new ArrayList<>();
                            CodeRuleService.App.getInstance().getSelect(new HashMap<>(), mapPage, new AsyncCallback<CodeRuleDto>() {
                                public void onSuccess(CodeRuleDto result) {
                                    List<Map<String, String>> keyValueMap = result.getKeyValueMap();
                                    for (Map<String, String> data : keyValueMap) {
                                        ListGridRecord record = new ListGridRecord();
                                        data.forEach((k, v) -> {
                                            record.setAttribute(k, v);
                                        });
                                        // 设置其他需要的属性
                                        recordList.add(record);

                                    }
                                    listGrid.setData(recordList.toArray(new ListGridRecord[0]));
                                    SC.say( "新增数据成功！");
                                    //list.addAll(result);
                                }

                                public void onFailure(Throwable caught) {
                                    SC.warn("获取数据失败！");
                                }
                            });
                        }

                        public void onFailure(Throwable caught) {
                            SC.warn("RPC failed");
                        }
                    });

                }
                winModal.hide();
            }
        });

        Button cancelButton = new Button("关闭");
        cancelButton.addClickHandler(event -> winModal.hide());


//        form.setFields(selectOtherItem);

        if (record != null) {
            db_model_idField.disable();
            form.setItems(db_model_idField,mcField,msField,fgfField,qzField,hzField,bbField);
        }else{
            form.setItems(db_model_idField,msField,fgfField,qzField,hzField,bbField);
        }

//        form.setItems(db_model_idField,mcField,msField,fgfField,qzField,hzField,bbField);
        winModal.addItem(form);

        HLayout buttonLayout = new HLayout();
        buttonLayout.setMembersMargin(10);
        buttonLayout.setAlign(Alignment.RIGHT);
        buttonLayout.setWidth100();
        buttonLayout.setHeight(30);
        buttonLayout.setPadding(5);
        buttonLayout.setLayoutAlign(VerticalAlignment.BOTTOM);
        if(istrue!=true){
            buttonLayout.addMembers(saveButton, cancelButton);

        }else {
            buttonLayout.addMembers( cancelButton);
        }
        winModal.addItem(buttonLayout);

        HStack layoutTopRow = new HStack(10);
        layoutTopRow.setHeight(50);

        VLayout layoutMain = new VLayout();
        layoutMain.addMember(layoutTopRow);

        layoutMain.draw();
        return winModal;
    }
    public static Map<String, String> convertRecordToMap(Record record) {
        JavaScriptObject jsObj = record.getJsObj();
        return JSOHelper.convertToMap(jsObj);
    }
}
